32. Quiz: Dictionaries and Identity Operators

Quiz: Define a Dictionary

Define a dictionary named population that contains this data:

Keys Values
Shanghai 17.8
Istanbul 13.3
Karachi 13.0
Mumbai 12.5

Start Quiz:

# Define a Dictionary, population,
# that provides information
# on the world's largest cities.
# The key is the name of a city
# (a string), and the associated
# value is its population in
# millions of people.

#   Key     |   Value
# Shanghai  |   17.8
# Istanbul  |   13.3
# Karachi   |   13.0
# Mumbai    |   12.5

Immutable Keys

Which of these could be used as the key for a dictionary? (Choose all that apply.)
Hint: Dictionary keys must be immutable, that is, they must be of a type that is not modifiable.

SOLUTION:
  • `str`
  • `int`
  • `float`

Quiz: Looking Up What Isn't There

What happens if we look up a value that isn't in the dictionary? Create a test dictionary and use the square brackets to look up a value that you haven't defined. What happens?

SOLUTION: A `KeyError` occurs

get with a Default Value

Dictionaries have a related method that's also useful, get() . get() looks up values in a dictionary, but unlike looking up values with square brackets, get() returns None (or a default value of your choice) if the key isn't found. If you expect lookups to sometimes fail, get() might be a better tool than normal square bracket lookups.

>>> elements.get('dilithium')
None
>>> elements['dilithium']
KeyError: 'dilithium'
>>> elements.get('kryptonite', 'There\'s no such element!')
"There's no such element!"

In the last example we specified a default value (the string 'There's no such element!') to be returned instead of None when the key is not found.

Checking for Equality vs. Identity: == vs. is

Checking for Equality vs. Identity

What will the output of the following code be? (Treat the commas in the multiple choice answers as newlines.)

a = [1, 2, 3]
b = a
c = [1, 2, 3]

print(a == b)
print(a is b)
print(a == c)
print(a is c)

There is a playground workspace further down this page that you can use to try it out.

SOLUTION: True, True, True, False

Start Quiz:

# Test the code here if you'd like
a = [1, 2, 3]
b = a
c = [1, 2, 3]